// src/stores/user.js
import { defineStore } from 'pinia'
import { login } from '@/utils/request'
import { setToken, removeToken } from '@/utils/auth'

export const useUserStore = defineStore('user', {
    state: () => ({
        username: '',
        token: ''
    }),
    getters: {
        isLoggedIn: (state) => !!state.token
    },
    actions: {
        // 修改后的登录方法（调用真实API）
        async login(credentials) {
            try {
                // 调用后端API
                const response = await login(credentials.username, credentials.password)

                // 假设后端返回的数据结构为 { code: 200, data: { token: 'xxx' } }
                if (response.code === 200) {
                    this.username = credentials.username
                    this.token = response.data.token
                    setToken(response.data.token) // 存储到localStorage
                    return Promise.resolve()
                } else {
                    return Promise.reject(response.message || '登录失败')
                }
            } catch (error) {
                // 处理网络错误或API错误
                return Promise.reject(error.response?.data?.message || '请求失败')
            }
        },

        // 退出登录（保持原有逻辑）
        logout() {
            this.token = ''
            this.username = ''
            removeToken()
        },

        // 初始化Token（保持原有逻辑）
        initTokenFromStorage() {
            const storedToken = getToken()
            if (storedToken) {
                this.token = storedToken
            }
        }
    }
})